<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/9/27 10:38
 */
include_once dirname(dirname(__FILE__)) . "/common.php";
\ns_core\m_load::load_old('nn_logic/cache/view_cache.class.php');
\ns_core\m_load::load_np('np_xml2array.class.php');

class m_completion
{
    public static $assets_info_completion_enabled =  false;
    public static $assets_info_completion_url =  '';
    public static $assets_info_completion_time =  1200;
    public static $no_need_change_info = true;//媒资补全的时候是否需要把 已经存在的信息替换   true 不替换 | false 需要替换

    /**
     * 初始化
     */
    public static function init()
    {
        global $g_assets_info_completion_enabled;
        global $g_assets_info_completion_url;
        global $g_assets_info_completion_time;
        self::$assets_info_completion_enabled = $g_assets_info_completion_enabled;
        self::$assets_info_completion_url = $g_assets_info_completion_url;
        if(isset($g_assets_info_completion_time) && (int)$g_assets_info_completion_time > 300)
        {
            self::$assets_info_completion_time = $g_assets_info_completion_time;
        }
        unset($g_assets_info_completion_enabled);
        unset($g_assets_info_completion_url);
        unset($g_assets_info_completion_time);
    }

    /**
     * 获取酷控媒资补全数据
     * @param $dc
     * @param $name
     * @param string $type
     * @param string $year
     * @param int $time
     * @return array  //array('ret', 'reason' 'data_info' => array())
     */
    public static function public_get_curl_completion_content($dc,$name,$type='',$year='',$time = 500)
    {
        if(!self::$assets_info_completion_enabled)
        {
            return \m_config::return_data(NS_CDS_FAIL, "媒资补全开关关闭");
        }
        //name进行URL编码
        $name = urlencode($name);
        $file_path = self::$assets_info_completion_url . "&name={$name}&type={$type}&year={$year}";
        $arr_cache_key_array = array(
            $file_path,
            $name,
            $type,
            $year
        );
        $str_cache_key = nl_view_cache::gkey('sync_source', $arr_cache_key_array);
        $view_cache = nl_view_cache::get($dc, $str_cache_key);
        if ($view_cache !== FALSE)
        {
            return \m_config::return_data(NS_CDS_SUCCE, "memcache hit", $view_cache);
        }

        //curl抓取 远程文件的内容
        ns_core\m_load::load_np('np_http_curl.class.php');
        $http_curl = new np_http_curl_class();
        $content = $http_curl->get($file_path);
        $curl_info = $http_curl->curl_getinfo();
        $http_code = $curl_info['http_code'];

        //如果内容为空  或者根本没这个xml文件
        if (empty($content) || !$content || $http_code >= 400)
        {
            $result = \m_config::return_data(NS_CDS_FAIL, "消息：curl获取媒资信息补全失败地址:" . $file_path . ';超时时间:' . $time.';http CODE:'.$http_code);
            nl_view_cache::set($dc, $str_cache_key, $result, self::$assets_info_completion_time);
            return $result;
        }

        $content = \m_config::trim_xml_header($content);
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($content);
        $xml = $dom->saveXML();
        unset($dom);
        $xml_arr = np_xml2array::getArrayData($xml);
        if ($xml_arr["ret"] == 0)
        {
            $result = \m_config::return_data(NS_CDS_FAIL, 'xml解析失败,内容为：' . var_export($xml, true));
            nl_view_cache::set($dc, $str_cache_key, $result,self:: $assets_info_completion_time);
            return $result;
        }
        if(!isset($xml_arr['data']['children'][0]['children']) || empty($xml_arr['data']['children'][0]['children']) || !is_array($xml_arr['data']['children'][0]['children']))
        {
            $result = \m_config::return_data(NS_CDS_FAIL, 'xml解析,内容为：' . var_export($xml_arr['data'], true));
            nl_view_cache::set($dc, $str_cache_key,$result, self::$assets_info_completion_time);
            return $result;
        }
        if(count($xml_arr['data']['children'][0]['children']) <= 1)
        {
            $result = \m_config::return_data(NS_CDS_SUCCE, 'OK');
            nl_view_cache::set($dc, $str_cache_key, $result, self::$assets_info_completion_time);
            return $result;
        }
        $content = self::make_completion_content($xml_arr['data']['children'][0]['children']);
        $result = \m_config::return_data(NS_CDS_SUCCE, 'api hit', $content['data_info']);

        nl_view_cache::set($dc, $str_cache_key, $result, self::$assets_info_completion_time);
        return $result;
    }

    /**
     * xml数据封装
     * @param $xml_arr
     * @return array //array('ret', 'reason' 'data_info' => array())
     */
    public static function make_completion_content($xml_arr)
    {
        $last_val = null;
        foreach ($xml_arr as $val)
        {
            if(!isset($val['name']) || strlen($val['name']) <1)
            {
                continue;
            }
            if(!in_array($val['name'], array('episodes','thumbs','pictures','cast_info','crews')))
            {
                $last_val[$val['name']] = isset($val['content']) ? $val['content'] : '';
                continue;
            }
            if(!is_array($val['children']) || empty($val['children']))
            {
                $last_val[$val['name']]=null;
            }
            if(!is_array($val['children']) || empty($val['children']))
            {
                continue;
            }
            //分集描述
            if($val['name'] =='episodes')
            {
                foreach ($val['children'] as $children_val)
                {
                    if(!isset($children_val['name']) || strlen($children_val['name']) <1 || $children_val['name'] !='episode' || !is_array($children_val['children']) || empty($children_val['children']))
                    {
                        continue;
                    }
                    $temp_index_val = null;
                    foreach ($children_val['children'] as $index_val)
                    {
                        if(!isset($index_val['name']) || strlen($index_val['name']) <1)
                        {
                            continue;
                        }
                        $temp_index_val[$index_val['name']] = isset($index_val['content']) ? $index_val['content'] : '';
                    }
                    if(!isset($temp_index_val['number']))
                    {
                        continue;
                    }
                    $last_val[$val['name']][$temp_index_val['number']] = $temp_index_val;
                }
            }
            //海报  剧照
            else if($val['name'] == 'thumbs' || $val['name'] =='pictures')
            {
                foreach ($val['children'] as $children_val)
                {
                    if(strpos($children_val['content'], '?') !== false)
                    {
                        $children_val['content'] = preg_replace('/\?.*/i', '', $children_val['content']);
                    }
                    if(isset($children_val['attributes']['size']) && strlen($children_val['attributes']['size'])>0 && $val['name'] == 'thumbs')
                    {
                        $arr_pic_size = explode('x', $children_val['attributes']['size']);
                        if(is_array($arr_pic_size) && !empty($arr_pic_size) && count($arr_pic_size) == 2)
                        {
                            $num = ceil(($arr_pic_size[0]/$arr_pic_size[1])*1000);
                            if ($num < 820)
                            {
                                $last_val[$val['name']]['verticality_img'] = $children_val['content'];
                                continue;
                            }
                            else if($num > 1300)
                            {
                                $last_val[$val['name']]['horizontal_img'] = $children_val['content'];
                                continue;
                            }
                        }
                    }
                    $last_val[$val['name']][] = $children_val['content'];
                }
            }
            // 明星
            else if($val['name'] =='cast_info')
            {
                $temp_index_val = array();
                foreach ($val['children'] as $children_val)
                {
                    if(!is_array($children_val['children']) || empty($children_val['children']))
                    {
                        continue;
                    }
                    foreach ($children_val['children'] as $index_val)
                    {
                        if(!isset($index_val['name']) || $index_val['name'] !='star_name')
                        {
                            continue;
                        }
                        $temp_index_val[] = $index_val['content'];
                    }
                }
                $last_val[$val['name']] = $temp_index_val;
            }
            //导演  作者
            else if($val['name'] =='crews')
            {
                foreach ($val['children'] as $children_val)
                {
                    if(!isset($children_val['attributes']['role']) || !in_array($children_val['attributes']['role'], array('writer','director')))
                    {
                        continue;
                    }
                    $temp_index_val = '';
                    if(!is_array($children_val['children']) || empty($children_val['children']))
                    {
                        continue;
                    }
                    foreach ($children_val['children'] as $index_val)
                    {
                        if(!isset($index_val['name']) || $index_val['name'] !='star_name' || !isset($index_val['content']) || strlen($index_val['content']) <1)
                        {
                            continue;
                        }
                        $temp_index_val = $index_val['content'];
                    }
                    $last_val[$children_val['attributes']['role']][] = $temp_index_val;
                }
            }
        }
        unset($xml_arr);
        return \m_config::return_data(NS_CDS_SUCCE, 'OK', $last_val);
    }


    /**
     * 封装获取到的数据
     * @param $content
     * @param $completion_content
     * @param bool $flag //true 主媒资| false分集
     * @param int $index //第几集
     * @return array //array('ret', 'reason' 'data_info' => array())
     */
    public static function public_make_completion_content($content,$completion_content,$flag=true,$index=0)
    {
        $index++;
        if(!is_array($completion_content) || empty($completion_content))
        {
            return \m_config::return_data(NS_CDS_SUCCE, 'OK', $content);
        }
        $arr_change_data = array(
            'AliasName'=>'title',
            'OriginalCountry'=>'area',
            'VolumnCount'=>'epi_no',
            'Description'=>'description',
            'ActorDisplay'=>'cast_info',
            'WriterDisplay'=>'writer',
            'DirectorDisplay'=>'director',
            'ReleaseYear'=>'release_year',
            'Kind'=>'genre',
            'Language'=>'language',
        );
        $arr_pic = array(
            'square_img',
            'smallpic',
            'middlepic',
            'bigpic',
        );
        $arr_pic_v2 = array(
            'verticality_img',
            'horizontal_img'
        );
        foreach ($arr_change_data as $change_key=>$change_val)
        {
            if((isset($content[$change_key]) && strlen($content[$change_key]) >0 && self::$no_need_change_info) || !isset($completion_content[$change_val]))
            {
                continue;
            }
            $content[$change_key] = isset($content[$change_key]) ? $content[$change_key] : '';
            if(in_array($change_key, array('ActorDisplay','WriterDisplay','DirectorDisplay')))
            {
                $completion_content[$change_val] = (is_array($completion_content[$change_val]) && !empty($completion_content[$change_val])) ? implode('/', $completion_content[$change_val]) : '';
            }
            else if($change_key == 'Kind')
            {
                $completion_content[$change_val] = str_replace(' ','/', $completion_content[$change_val]);
            }
            $content[$change_key] = (strlen($completion_content[$change_val]) >0) ? $completion_content[$change_val] : $content[$change_key];
        }
        $temp_completion_data_pic = (isset($completion_content['thumbs']) && is_array($completion_content['thumbs']) && !empty($completion_content['thumbs'])) ? $completion_content['thumbs'] : null;
        $temp_completion_data_pic_no_des = $temp_completion_data_pic_des = null;
        if(is_array($temp_completion_data_pic))
        {
            foreach ($temp_completion_data_pic as $key=>$val)
            {
                if(is_int($key))
                {
                    $temp_completion_data_pic_des[] = $val;
                }
                else
                {
                    $temp_completion_data_pic_no_des[$key] = $val;
                }
            }
        }
        unset($temp_completion_data_pic);
        if(!$flag)
        {
            $arr_pic = array('pic');
            $arr_pic_v2 = null;
            if((!isset($content['Description']) || strlen($content['Description'])<1 || !self::$no_need_change_info) && isset($completion_content['episodes'][$index]['description']) && strlen(isset($completion_content['episodes'][$index]['description'])) >0)
            {
                $content['Description'] = $completion_content['episodes'][$index]['description'];
            }
            if((!isset($content['ViewPoint']) || strlen($content['ViewPoint'])<1 || !self::$no_need_change_info) && isset($completion_content['episodes'][$index]['title']) && strlen(isset($completion_content['episodes'][$index]['title'])) >0)
            {
                $content['ViewPoint'] = $completion_content['episodes'][$index]['title'];
            }
        }
        else
        {
            if(!isset($content['verticality_img']) || strlen($content['verticality_img']) <1)
            {
                if(isset($temp_completion_data_pic_no_des['verticality_img']) && strlen($temp_completion_data_pic_no_des['verticality_img'])>0)
                {
                    $content['verticality_img'] = $temp_completion_data_pic_no_des['verticality_img'];
                }
                else if(is_array($temp_completion_data_pic_des) && !empty($temp_completion_data_pic_des))
                {
                    $content['verticality_img'] = array_shift($temp_completion_data_pic_des);
                }
            }
            if(!isset($content['horizontal_img']) || strlen($content['horizontal_img']) <1)
            {
                if(isset($temp_completion_data_pic_no_des['horizontal_img']) && strlen($temp_completion_data_pic_no_des['horizontal_img'])>0)
                {
                    $content['horizontal_img'] = $temp_completion_data_pic_no_des['horizontal_img'];
                }
                else if(is_array($temp_completion_data_pic_des) && !empty($temp_completion_data_pic_des))
                {
                    $content['horizontal_img'] = array_shift($temp_completion_data_pic_des);
                }
            }
        }
        if(!empty($arr_pic_v2) && is_array($arr_pic_v2))
        {
            foreach ($arr_pic_v2 as $val)
            {
                if((isset($content[$val]) && strlen($content[$val]) >0 && self::$no_need_change_info) || (isset($content[$val]) && strlen($content[$val]) >0))
                {
                    continue;
                }
                if(isset($temp_completion_data_pic_no_des[$val]) && strlen($temp_completion_data_pic_no_des[$val])>0)
                {
                    $content[$val] = $temp_completion_data_pic_no_des[$val];
                }
                else if(is_array($temp_completion_data_pic_des) && !empty($temp_completion_data_pic_des))
                {
                    $content[$val] = array_shift($temp_completion_data_pic_des);
                }
            }
        }
        foreach ($arr_pic as $pic_key=>$pic_value)
        {
            if((isset($content[$pic_value]) && strlen($content[$pic_value])>0) && self::$no_need_change_info)
            {
                unset($arr_pic[$pic_key]);
            }
        }
        if(empty($arr_pic) || !is_array($arr_pic))
        {
            unset($completion_content);
            return \m_config::return_data(NS_CDS_SUCCE, 'OK', $content);
        }
        $arr_pic = array_values($arr_pic);

        foreach ($arr_pic as $pic_value)
        {
            if(!isset($completion_content['pictures']) || !is_array($completion_content['pictures']) || empty($completion_content['pictures']))
            {
                break;
            }
            $content[$pic_value] = array_shift($completion_content['pictures']);
        }
        unset($completion_content);
        return \m_config::return_data(NS_CDS_SUCCE, 'OK', $content);
    }


    /**
     * 酷控补全媒资类型规整
     * @param $view_type
     * @return int
     */
    public static function get_temp_view_type($view_type)
    {
        $temp_view_type = 2;
        if(strlen($view_type) <1)
        {
            return $temp_view_type;
        }
        if(in_array($view_type, array('2')))
        {
            $temp_view_type = 3;
        }
        else if(in_array($view_type, array('1')))
        {
            $temp_view_type = 1;
        }
        else if(in_array($view_type, array('7')))
        {
            $temp_view_type = 4;
        }
        return $temp_view_type;
    }
}